#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int threeSumClosest(vector<int>& nums, int target) {
    //排序后先枚举元素a
    sort(nums.begin(), nums.end());
    int sumClosest = nums[0]+nums[1]+nums[nums.size()-1];
    int a = 0;
    for(int i=0;i<nums.size()-2;i++)
    {
        a = nums[i];
        int min = i+1;
        int max = nums.size()-1;
        while(min<max-1)
        {
            if(a+nums[min]+nums[max]==target)
                return target;
            else if(a+nums[min]+nums[max]>target)
                max--;
            else
                min++;
        }
        if(abs(a+nums[min]+nums[max]-target)<abs(sumClosest-target))
            sumClosest = a+nums[min]+nums[max];
        cout<<"a: "<<a<<" min: "<<min<<" max: "<<max<<" sumClosest: "<<sumClosest<<endl;
    }
    return sumClosest;
}

int main()
{
    vector<int> v;
    cout<<"Enter a list of integers: "<<endl;
    for(int i=0;i<4;i++)
    {
        int x;
        cin>>x;
        v.push_back(x);
    }
    cout<<"target: "<<endl;
    int target;
    cin>>target;
    int result = threeSumClosest(v,target);
    cout<<"result: "<<result;
    return 0;
}